﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class TaoBaoApi_TB_UploadBB2 : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Page.Theme = BLL.Common.GetWSMThemes();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTypeRoot();
            BindDiqu();
            string user = Request.QueryString["user"];
            string spdm = Request.QueryString["spdm"];
            if (user == null || spdm == null || user.Length == 0 || spdm.Length == 0)
            {
                new TBCommon().ShowMessage(Page, "输入参数非法，操作被终止。");
                return;
            }
            txtUser.Text = user;
            BindLeiMu(spdm);
            BindSPInfo(spdm);
        }
    }
    /// <summary>
    /// 由商品代码，到tb_baobei中搜索，如果找到，则绑定此宝贝的分类。

    /// </summary>   
    void BindLeiMu(string spdm)
    {       
        List<Model.TaoBao.TB_BAOBEI> bs = new BLL.TaoBao.TB_BAOBEI().GetAllList();
        foreach(Model.TaoBao.TB_BAOBEI b in bs)
            if (b.field2 == spdm)
            {//说明已和宝贝绑定
                string cid = b.LMDM;
                int MID = new TBCommon().GetTBLeiMuMID(cid);
                //获取props
                //txtProps.Text = new TBCommon().GetPropsbyMid(b.MID);
                Model.TaoBao.TB_LEIMU m = new BLL.TaoBao.TB_LEIMU().GetModel(MID);
                if (m != null)
                {
                    if (m.PARENTID == 0)
                        ddlType1.Text = m.MID.ToString();
                    else
                        if (!new TBCommon().ISHasChildByMID(MID))
                        {
                            ddlType3.Items.Clear();
                            List<Model.TaoBao.TB_LEIMU> ms = new BLL.TaoBao.TB_LEIMU().GetAllList();
                            foreach (Model.TaoBao.TB_LEIMU mm in ms)
                                if (!new TBCommon().ISHasChildByMID(mm.MID))
                                    ddlType3.Items.Add(new ListItem(mm.LMMC, mm.MID.ToString()));
                            ddlType3.Text = m.MID.ToString();
                        }
                }
            }
        //ddlType1.Text = "2262";
    }
    void BindSPInfo(string spdm)
    {
        Model.SHANGPIN sp = new BLL.SHANGPIN().GetModel(spdm);
        if (sp == null)
            return;
        
        txtTitle.Text = sp.SPMC;
        txtPrice.Text = string.Format("{0:0.00}", sp.BZSJ);
        //txtNum.Text = sp.BZSL.ToString();
    }
    void BindDiqu()
    {
        List<Model.TaoBao.TB_DIQU> dqs = new BLL.TaoBao.TB_DIQU().GetAllList();
        ddlProvince.Items.Clear();
        ddlCity.Items.Clear();
        foreach (Model.TaoBao.TB_DIQU d in dqs)
            if(d.PARENTID==0)
                ddlProvince.Items.Add(new ListItem(d.DQMC,d.MID.ToString()));
    }

    //绑定淘宝类目
    void BindTypeRoot()
    {
        List<Model.TaoBao.TB_LEIMU> tbs = new BLL.TaoBao.TB_LEIMU().GetAllList();
        ddlType1.Items.Clear();
        foreach (Model.TaoBao.TB_LEIMU m in tbs)
            if (m.PARENTID == 0)
                ddlType1.Items.Add(new ListItem(m.LMMC, m.MID.ToString()));
    }
    protected void ddlType1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlType1.SelectedIndex > -1)
        {
            List<Model.TaoBao.TB_LEIMU> tbs = new BLL.TaoBao.TB_LEIMU().GetAllList();
            ddlType2.Items.Clear();          
            foreach (Model.TaoBao.TB_LEIMU m in tbs)
                if (m.PARENTID == Convert.ToInt32(ddlType1.SelectedValue))
                    ddlType2.Items.Add(new ListItem(m.LMMC, m.MID.ToString()));
            ddlType3.Items.Clear();           
        }
    }
    protected void ddlType2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlType2.SelectedIndex > -1)
        {
            List<Model.TaoBao.TB_LEIMU> tbs = new BLL.TaoBao.TB_LEIMU().GetAllList();
            ddlType3.Items.Clear();       
            foreach (Model.TaoBao.TB_LEIMU m in tbs)
                if (m.PARENTID == Convert.ToInt32(ddlType2.SelectedValue))
                    ddlType3.Items.Add(new ListItem(m.LMMC, m.MID.ToString()));          
        }
    }

    protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlProvince.SelectedIndex > -1)
        {
            ddlCity.Items.Clear();
            List<Model.TaoBao.TB_DIQU> dqs = new BLL.TaoBao.TB_DIQU().GetAllList();
            foreach (Model.TaoBao.TB_DIQU d in dqs)
                if (d.PARENTID.ToString() == ddlProvince.SelectedValue)
                    ddlCity.Items.Add(new ListItem(d.DQMC, d.MID.ToString()));
        }
    }
    string GetCid()
    {
        if (ddlType3.SelectedIndex < 0)
        {
            if (ddlType2.SelectedIndex < 0)
                if (ddlType1.SelectedIndex < 0)
                    return null;
                else
                    return new BLL.TaoBao.TB_LEIMU().GetModel(Convert.ToInt32(ddlType1.SelectedValue)).LMDM;
            else
                return new BLL.TaoBao.TB_LEIMU().GetModel(Convert.ToInt32(ddlType2.SelectedValue)).LMDM;
        }
        else
            return new BLL.TaoBao.TB_LEIMU().GetModel(Convert.ToInt32(ddlType3.SelectedValue)).LMDM;
    }
    bool CheckInput()
    {
        return true;
    }
    //发布宝贝
    protected void btnUp_Click(object sender, EventArgs e)
    {
        //获取宝贝参数
        string title = txtTitle.Text.TrimEnd();
        string num = txtNum.Text.TrimEnd();
        string price = txtPrice.Text.TrimEnd();
        string approveStatus = radioApproveStatus.SelectedValue;
        string cid = GetCid();
        string type = radioType.SelectedValue;
        string stuffStatus = radioStuffStatus.SelectedValue;
        string state = ddlProvince.SelectedItem.Text;
        string city = ddlCity.SelectedItem.Text;
        string freight = radioFreight.SelectedValue;
        string post = txtPostFee.Text.TrimEnd();
        string express = txtExpress.Text.TrimEnd();
        string ems = txtEMS.Text.TrimEnd();
        string valid = radioValid.SelectedValue;
        string has_invoice = chkInvoice.Checked ? "true" : "false";
        string has_warranty = chkShowCase.Checked ? "true" : "false";
        string has_discount = chkDiscount.Checked ? "true" : "false";
        string auto_repost = chkAutoRepost.Checked ? "true" : "false";
        string has_showcase = chkShowCase.Checked ? "true" : "false";
        string list_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string desc = web1.Text;
        //string props = txtProps.Text.TrimEnd();
        //props = props.Substring(0, props.Length - 1);
        if (!CheckInput())
            return;      
        byte [] bufImg=null;
        if(fileImg.HasFile)
        {
            string imgPath = fileImg.PostedFile.FileName;
            FileStream imgFile = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
            bufImg = new byte[(int)imgFile.Length];
            imgFile.Read(bufImg, 0, bufImg.Length);
            imgFile.Close();
        }        
        string username = txtUser.Text;
        string password = new TBCommon().GetTBPsdbyZH(username);
        string appkey = new TaoBaoAPI().GetAppKey(username);
        string certcode = new TaoBaoAPI().GetCertCode(username);
        string sessionId = null;
        string errMsg = null;
        int ret = new TaoBaoAPI().GetTBSessionId(Page, username, password, appkey, ref errMsg, ref sessionId);
        if (ret != 0)
        {
            new TBCommon().ShowMessage(Page, errMsg);
            return;
        }
        string[,] param = null;
        if(freight=="seller")
            param = new string[,] { { "nick",username  }, { "method", "taobao.item.add" },{ "v", "1.0" }, { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, 
                { "format", "xml" },{"app_key",appkey},{"approve_status",approveStatus},{"cid",cid},{"num",num},{"price",price},{"type",type},{"stuff_status",stuffStatus},
                {"title",title},{"desc",desc },{"location.state",state},{"location.city",city},{"freight_payer",freight},
                {"valid_thru",valid},{"has_invoice",has_invoice},{"has_discount",has_discount},{"auto_repost",auto_repost},{"has_showcase",has_showcase}};
        else
            param = new string[,] { { "nick",username  }, { "method", "taobao.item.add" },{ "v", "1.0" }, { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, 
                { "format", "xml" },{"app_key",appkey},{"approve_status",approveStatus},{"cid",cid},{"num",num},{"price",price},{"type",type},{"stuff_status",stuffStatus},
                {"title",title},{"desc",desc },{"location.state",state},{"location.city",city},{"freight_payer",freight},{"post_fee",post},{"express_fee",express},{"ems_fee",ems},
                {"valid_thru",valid},{"has_invoice",has_invoice},{"has_discount",has_discount},{"auto_repost",auto_repost},{"has_showcase",has_showcase}};
        BS2.BSTaobaoAPI.BSTaobaoItemAddBus addBus = new TB_UploadBB().UploadBaoBei(username, password, appkey, certcode, sessionId, param, bufImg);
        if (addBus._created==null||addBus._iid==null)
        {
            new TBCommon().ShowMessage(Page, "上传商品失败，错误代码：600023。");
            return;
        }
        new TBCommon().ShowMessage(Page, "上传宝贝成功，宝贝ID："+addBus._iid +"，时间："+addBus._created);
    }
    //运费承担方

    protected void radioFreight_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (radioFreight.SelectedValue == "buyer")
            txtEMS.Enabled = txtExpress.Enabled = txtPostFee.Enabled = true;
        else
            txtEMS.Enabled = txtExpress.Enabled = txtPostFee.Enabled = false;
    }
}
